using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace Raptor.Client
{
  public partial class frmMergeDO : Form
  {
    private SqlConnection m_ActiveConn;
    //private bool bParentSelected = false;
    /// <summary>
    /// Active Connection
    /// </summary>
    public SqlConnection ActiveConn
    {
      get { return m_ActiveConn; }
      set { m_ActiveConn = value; }
    }
		
    /// <summary>
    /// Form
    /// </summary>
    public frmMergeDO()
    {
      InitializeComponent();
    }

    private void frmMergeDO_Load(object sender, EventArgs e)
    {
      LoadAllGeneratedDOs();
    }

    private void LoadAllGeneratedDOs()
    {
      DataSet DSGenObj = new DataSet();
      string sSQLString = "";

      if (ActiveConn.State == ConnectionState.Closed)
      {
        ActiveConn.Open();
      }

      sSQLString = "SELECT * FROM GenerateObject ORDER BY GenerateObject_Name";

      SqlDataAdapter SQA = new SqlDataAdapter(sSQLString, ActiveConn);

      try
      {
        SQA.Fill(DSGenObj);

        if (DSGenObj.Tables[0].Rows.Count > 0)
        {
          foreach (DataRow dr in DSGenObj.Tables[0].Rows)
          {
            DGParent.Rows.Add(false, dr["GenerateObject_Name"].ToString(), dr["GenerateObject_ID"].ToString());
            DGMergeDO.Rows.Add(false, dr["GenerateObject_Name"].ToString(), dr["GenerateObject_ID"].ToString());
          }
        }
      }
      catch (SqlException ex)
      {
        MessageBox.Show(ex.Message, "Oops", MessageBoxButtons.OK);
      }
    }

    private void DGParent_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex >= 0)
      {
        if (bool.Parse((DGParent.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
          (DGMergeDO.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = false;
          DGMergeDO.Rows[e.RowIndex].Visible = false;
          DGParent.Enabled = false;
          DGMergeDO.Enabled = true;
        }
        ReloadMergedSelection();
     }
    }

    private void DGParent_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
      DGParent.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange);
    }

    private void DGMergeDO_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex >= 0)
      {
        if (bool.Parse((DGMergeDO.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
        }
        ReloadMergedSelection();
      }
    }

    private void ReloadMergedSelection()
    {
      DGMergedSelection.Rows.Clear();
      foreach (DataGridViewRow row in DGParent.Rows)
      {
        if(bool.Parse((row.Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
          DGMergedSelection.Rows.Add(true, row.Cells[1].Value, row.Cells[2].Value);
        }
      }

      foreach (DataGridViewRow row in DGMergeDO.Rows)
      {
        if(bool.Parse((DGMergeDO.Rows[row.Index].Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
          DGMergedSelection.Rows.Add(false, row.Cells[1].Value, row.Cells[2].Value);
        }
      }
    }

    private void DGMergeDO_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
      DGMergeDO.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange);
    }

    private void btnNewParent_Click(object sender, EventArgs e)
    {
      foreach (DataGridViewRow row in DGParent.Rows)
      {
        (DGParent.Rows[row.Index].Cells[0] as DataGridViewCheckBoxCell).Value = false;
        DGMergeDO.Enabled = false;
        DGParent.Enabled = true;
      }

      foreach (DataGridViewRow row in DGMergeDO.Rows)
      {
        DGMergeDO.Rows[row.Index].Visible = true;
      }
    }

    private void btnMerge_Click(object sender, EventArgs e)
    {
      string sSQLString = "";
      string sCreateSQLString = "";
      string sFieldName = "";

      if (txtMergeDoName.Text.Trim().Length == 0)
      {
        MessageBox.Show("Please specify a name for the new merged DO!", "Name", MessageBoxButtons.OK);
        return;
      }

      foreach (DataGridViewRow row in DGMergedSelection.Rows)
      {
        DataSet DSResult = new DataSet();

        //sTableMergeName += row.Cells[1].Value.ToString();
        sSQLString = "SELECT * FROM SearchParameter WHERE GenerateObject_ID = " + row.Cells[2].Value.ToString();

        SqlDataAdapter SQA = new SqlDataAdapter(sSQLString, ActiveConn);

        try
        {
          SQA.Fill(DSResult);

          if (DSResult.Tables[0].Rows.Count > 0)
          {
            foreach (DataRow dr in DSResult.Tables[0].Rows)
            {
              string sFieldType = dr["SearchParameter_DataType"].ToString();
              string sIsNullable = "null";
              string sPrimaryKey = "";
              if(sFieldType == "varchar")
              {
                sFieldType += " (" + dr["SearchParameter_FieldLength"].ToString() + ")";
              }
              if(bool.Parse(dr["SearchParameter_IsNullable"].ToString()))
              {
                sIsNullable = "not null";
              }
              if (bool.Parse(dr["SearchParameter_IsPrimaryKey"].ToString()))
              {
                sPrimaryKey = dr["SearchParameter_FieldName"].ToString();
                sFieldName = "PK_" + dr["SearchParameter_FieldName"].ToString();
              }
              else
              {
                sPrimaryKey = "";
                sFieldName = dr["SearchParameter_FieldName"].ToString();
              }

              if (sCreateSQLString.IndexOf(sFieldName) > 0)
              {
                sFieldName = row.Cells[1].Value.ToString() + sFieldName;
              }

              sCreateSQLString += "\t" + sFieldName + " " + sFieldType + " " + sIsNullable + ",\r\n";

              //if ((sPrimaryKey.Length == 0) || (sPrimaryKey.Length > 0 && sCreateSQLString.IndexOf(sPrimaryKey) == -1))
              //{
              //  sCreateSQLString += "\t" + dr["SearchParameter_FieldName"].ToString() + " " + sFieldType + " " + sIsNullable + ",\r\n";
              //}
              //else
              //{
              //  sCreateSQLString += "\tPK_" + dr["SearchParameter_FieldName"].ToString() + " " + sFieldType + " " + sIsNullable + ",\r\n";
              //}
            }
          }
        }
        catch (SqlException ex)
        {
          MessageBox.Show(ex.Message, "Oops", MessageBoxButtons.OK);
        }
      }
      sCreateSQLString = sCreateSQLString.Substring(1, sCreateSQLString.LastIndexOf(",") -1);
      sCreateSQLString = "CREATE TABLE " + txtMergeDoName.Text + "\r\n(\r\n\t" + sCreateSQLString + "\r\n)";

      SqlCommand CreateComm = new SqlCommand(sCreateSQLString, ActiveConn);
      CreateComm.ExecuteNonQuery();
    }
  }
}